﻿using Apps.Common;
using Apps.Model;
using Apps.Repository.UnitOfWork;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Apps.Repository
{
    public class BaseRepository<TEntity, TKey> : IBaseRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>
    {
        private readonly SqlDbContext _context;
        private readonly DbSet<TEntity> _dbSet;
        public BaseRepository(SqlDbContext context)
        {
            _context = context;
            _dbSet = context.Set<TEntity>();
        }


        public async Task AddAsync(TEntity entity)
        {
            await _dbSet.AddAsync(entity);

        }

        public async Task AddRangeAsync(IEnumerable<TEntity> entities)
        {
            await _dbSet.AddRangeAsync(entities);
        }

        public async Task DeleteAsync(TEntity entity)
        {
            _dbSet.Remove(entity);
        }

        public async Task DeleteRangeAsync(IEnumerable<TEntity> entities)
        {
            _dbSet.RemoveRange(entities);
        }
        public async Task UpdateAsync(TEntity entity)
        {
            _context.Entry(entity).State = EntityState.Modified;
        }

        public async Task UpdateRangeAsync(IEnumerable<TEntity> entities)
        {
            _context.UpdateRange(entities);
        }


        public async Task<TEntity?> GetByIdAsync(TKey id)
        {
            return await _dbSet.FindAsync(id);
        }

        public async Task<List<TEntity>> GetAllAsync()
        {
            return await _dbSet.ToListAsync();
        }

        public async Task<IEnumerable<TEntity>> GetAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await _dbSet.Where(predicate).ToListAsync();
        }

        public async Task<PagedResult<TEntity>> GetPagedAsync( int pageIndex, int pageSize, Expression<Func<TEntity, bool>>? predicate = null)
        {
            if (predicate == null)
            {
                var totalCount = await _dbSet.CountAsync();

                var items = await _dbSet.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
                return new PagedResult<TEntity>(items, totalCount, pageIndex, pageSize);
            }
            else
            {
                var totalCount = await _dbSet.Where(predicate).CountAsync();
                var items = await _dbSet.Where(predicate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
                return new PagedResult<TEntity>(items, totalCount, pageIndex, pageSize);
            }

           
        }

        public async Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await _dbSet.AnyAsync(predicate);
        }
    }
}
